#include <vector>
#include <unordered_map>
#include <functional>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    vector<int> rightSideView(TreeNode *root)
    {
        vector<int> res;
        unordered_map<int, int> u_map;
        function<int(TreeNode *, int)> func = [&](TreeNode *root, int level) -> int
        {
            if (!root)
                return level;
            if (root)
                u_map[level] = root->val;
            return max(func(root->left, level + 1), func(root->right, level + 1));
        };
        int level_end = func(root, 0);
        for (int i = 0; i < level_end; i++)
        {
            res.emplace_back(u_map[i]);
        }
        return res;
    }
};
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int>res;
        function<void(TreeNode*,int)> func=[&](TreeNode* root,int level){
            if(!root)return ;
            if(root&&level>=res.size())
                res.emplace_back(root->val);
            func(root->right,level+1);
            func(root->left,level+1);
        };
        func(root,0);
        return res;
    }
};